package utils;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.*;

public class XmlUtil {
	public NodeList getNodeByTagName(String fileName,String tagName) {
		NodeList list=null;
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(new File(fileName));
			Element rootElement = document.getDocumentElement();

			list = rootElement.getElementsByTagName(tagName);
			//Element element = (Element) list.item(0);
			//System.out.println(element.getChildNodes().item(0).getNodeValue());

		} catch (Exception e) {
			System.out.println("exception:" + e.getMessage());
		}
		return list;
	}
	
	public Element getElementByAttr(String fileName,String attrName,String attrValue){
		Element rst=null;
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(new File(fileName));
			Element rootElement = document.getDocumentElement();

			NodeList list = rootElement.getChildNodes();
			for(int i=0;i<list.getLength();i++){		
				Node nd=list.item(i);
				Element element=(Element)list.item(i);	
				
				if(element.getAttribute(attrName).equals(attrValue)){
					rst=element;
					break;
				}
			}
			 //element = (Element) list.item(0);
			//System.out.println(element.getChildNodes().item(0).getNodeValue());

		} catch (Exception e) {
			System.out.println("exception:" + e.getMessage());
		}
		return rst;
	}
}
